const cloud = require('@cloudbase/node-sdk')

// 初始化云开发实例
const app = cloud.init({
    env: cloud.SYMBOL_CURRENT_ENV
})

// 获取数据库引用
const db = app.database()
const collection = db.collection('case_resume_template')

/**
 * case_resume_template CRUD 云函数
 * @param {Object} event - 云函数参数
 * @param {Object} context - 云函数上下文
 */
exports.main = async (event, context) => {
    const { action, data } = event

    try {
        // 操作日志
        console.log('case-resume-template-crud 调用:', { action, data })

        switch (action) {
            case 'create':
                return await createTemplate(data)
            case 'read':
                return await getTemplate(data)
            case 'update':
                return await updateTemplate(data)
            case 'delete':
                return await deleteTemplate(data)
            case 'list':
                return await listTemplates(data)
            default:
                throw new Error('无效的操作类型')
        }
    } catch (error) {
        console.error('case-resume-template-crud 错误:', error)
        return {
            code: -1,
            message: error.message,
            data: null
        }
    }
}

// 创建简历模板
async function createTemplate(data) {
    const { name, content, isPublic } = data

    if (!name || !content) {
        throw new Error('名称和内容为必填项')
    }

    const result = await collection.add({
        name,
        content,
        isPublic: isPublic || false,
        createdAt: new Date(),
        updatedAt: new Date(),
        usageCount: 0
    })

    return {
        code: 0,
        message: '创建成功',
        data: result
    }
}

// 获取单个模板
async function getTemplate(data) {
    const { id } = data

    if (!id) {
        throw new Error('ID为必填项')
    }

    const result = await collection.doc(id).get()

    if (!result.data || result.data.length === 0) {
        throw new Error('模板不存在')
    }

    return {
        code: 0,
        message: '查询成功',
        data: result.data[0]
    }
}

// 更新模板
async function updateTemplate(data) {
    const { id, name, content, isPublic } = data

    if (!id) {
        throw new Error('ID为必填项')
    }

    const updateData = {
        updatedAt: new Date()
    }

    if (name) updateData.name = name
    if (content) updateData.content = content
    if (isPublic !== undefined) updateData.isPublic = isPublic

    const result = await collection.doc(id).update(updateData)

    return {
        code: 0,
        message: '更新成功',
        data: result
    }
}

// 删除模板
async function deleteTemplate(data) {
    const { id } = data

    if (!id) {
        throw new Error('ID为必填项')
    }

    const result = await collection.doc(id).remove()

    return {
        code: 0,
        message: '删除成功',
        data: result
    }
}

// 获取模板列表
async function listTemplates(data) {
    const { page = 1, pageSize = 10, isPublic } = data

    const query = collection.where({})

    if (isPublic !== undefined) {
        query.where({ isPublic })
    }

    const result = await query
        .orderBy('createdAt', 'desc')
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .get()

    const countResult = await query.count()

    return {
        code: 0,
        message: '查询成功',
        data: {
            list: result.data,
            total: countResult.total,
            page,
            pageSize
        }
    }
}